package com.weichen.xd;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.weichen.xd.data.City;

/**
 * Created by Dune on 2017/9/6.
 */

public class CityAdapter extends BaseAdapter {

    private City[] cities;

    public CityAdapter(City[] cities) {
        this.cities = cities;
    }

    @Override
    public int getCount() {
        return cities == null ? 0 : cities.length;
    }

    @Override
    public Object getItem(int position) {
        return cities[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder holder;

        Log.e("adapter view ", String.valueOf(convertView == null));

        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            view = inflater.inflate(R.layout.item_city_info, parent, false);
            holder = new ViewHolder(view);
            view.setTag(holder);

        } else {

            holder = (ViewHolder) view.getTag();
        }

        City city = (City) getItem(position);

        holder.tvCityName.setText(city.getCity());
        holder.tvCityProv.setText(city.getProv());

        holder.tvCityLatLon.setText(parent.getContext().getString(R.string.format_lat_lon,
                city.getLon(), city.getLat()));


        return view;
    }


    private static class ViewHolder {

        TextView tvCityName;
        TextView tvCityProv;
        TextView tvCityLatLon;

        public ViewHolder(View view) {
            tvCityName = (TextView) view.findViewById(R.id.tv_city_name);
            tvCityProv = (TextView) view.findViewById(R.id.tv_prov);
            tvCityLatLon = (TextView) view.findViewById(R.id.tv_lat_lon);
        }
    }
}
